package cn.wmingming.e3mall.sso.service.impl;

import cn.wmingming.common.jedis.JedisClient;
import cn.wmingming.common.pojo.E3Result;
import cn.wmingming.common.utils.JsonUtils;
import cn.wmingming.e3mall.mapper.TbUserMapper;
import cn.wmingming.e3mall.pojo.TbUser;
import cn.wmingming.e3mall.pojo.TbUserExample;
import cn.wmingming.e3mall.sso.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Huangzm
 * @create 2018/06/22 9:48
 * @desc
 * @Modified By:
 **/

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private TbUserMapper userMapper;
    @Autowired
    private JedisClient jedisClient;
    @Value("${REDIS_SESSION_EXPIRE}")
    private Integer REDIS_SESSION_EXPIRE;
    @Value("${TOKEN_PRE}")
    private String TOKEN_PRE;


    @Override
    public E3Result checkParam(String param, Integer type) {
        //1 用户名 2手机号 3邮箱
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        List<TbUser> userList = new ArrayList<>();
        if(type == 1){
            criteria.andUsernameEqualTo(param);
            userList = userMapper.selectByExample(example);
        }else if(type == 2){
            criteria.andPhoneEqualTo(param);
            userList = userMapper.selectByExample(example);

        }else if(type == 3){
            criteria.andEmailEqualTo(param);
            userList = userMapper.selectByExample(example);

        }
        if(userList == null || userList.size() >= 1){
            E3Result result = E3Result.build(10023, "用户名已经被占用");
            result.setData(false);
            return result;

        }
        E3Result result = E3Result.ok();
        result.setData(true);
        return result;
    }

    @Override
    public E3Result register(TbUser user) {
        //数据有效性校验
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())
                || StringUtils.isBlank(user.getPhone())) {
            return E3Result.build(400, "用户数据不完整，注册失败");
        }
        //1：用户名 2：手机号 3：邮箱
        E3Result result = checkParam(user.getUsername(), 1);
        if (!(boolean) result.getData()) {
            return E3Result.build(400, "此用户名已经被占用");
        }
        result = checkParam(user.getPhone(), 2);
        if (!(boolean)result.getData()) {
            return E3Result.build(400, "手机号已经被占用");
        }
        //补全pojo的属性
        user.setCreated(new Date());
        user.setUpdated(new Date());
        //对密码进行MD5加密
        String md5Pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass);
        userMapper.insert(user);
        return E3Result.ok();
    }

    @Override
    public E3Result login(String username, String password) {
        //1 检验数据
        if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            return E3Result.build(10056,"数据错误");
        }
        //2 数据库查询是否该账号，密码是否相同
        TbUserExample example = new TbUserExample();
        example.createCriteria().andUsernameEqualTo(username).andPasswordEqualTo(DigestUtils.md5DigestAsHex(password.getBytes()));
        List<TbUser> userList = userMapper.selectByExample(example);
        if(userList == null || userList.size() == 0) {
            return E3Result.build(10055,"用户名或密码错误");
        }
        //3 若相同，用redis模拟session，保存用户信息到redis,并设置过期时间
        String token = UUID.randomUUID().toString();
        jedisClient.set(TOKEN_PRE+token,JsonUtils.objectToJson(userList.get(0)));
        jedisClient.expire(TOKEN_PRE+token,REDIS_SESSION_EXPIRE);
        //4 返回E3Result,数据为200和key
        return E3Result.ok(token);
    }

    @Override
    public E3Result getUserByToken(String token) {
        //从redis中查询token
        String userJson = jedisClient.get(TOKEN_PRE + token);
        if (StringUtils.isBlank(userJson)){
            //若不存在，返回用户登陆过期
            return E3Result.build(1452,"用户登陆过期");
        }
        //若存在，重置过期时间
        jedisClient.expire(TOKEN_PRE+token,REDIS_SESSION_EXPIRE);
        return E3Result.ok(JsonUtils.jsonToPojo(userJson,TbUser.class));
    }
}
